<?php

namespace app\coupons\controller;

use library\Controller;
use think\Db;
use think\facade\Request;


/** 积分等级
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/11/18
 * Time: 21:07
 */

class ScoreLevel extends Controller
{
    protected $table = 'lite_score_level';

    //积分等级首页
    public function index()
    {
        $this->title = '积分等级管理';
        $where = ['is_deleted' => 0];
        $this->_query($this->table)->like('name')->where($where)->order('id', 'desc')->page();
    }


    //添加积分等级
    public function add()
    {
        $this->title = '添加积分等级';
        $this->isAddMode = '1';
        $this->applyCsrfToken();
        return $this->_form($this->table, 'form');
    }

    public function edit()
    {
        $this->title = '编辑积分等级';
        $this->isAddMode = '0';
        $this->applyCsrfToken();
        return $this->_form($this->table, 'form');
    }

    public function del()
    {
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }


    public function _form_filter(&$data)
    {
        if ($this->request->isGet()) {

        } elseif ($this->request->isPost()) {
            $data['create_time'] = date('Y-m-d H:i:s');

        }
    }


    //关联服务
    public function addPrivilege()
    {
        $levelId = $this->request->param('level_id');
        if(Request::instance()->isGet()){
            $privilege = db('lite_score_privilege')->where(['is_deleted' => 0])->column('id, title', 'id');
            //已有數據
            $hasPrivilege = db('lite_score_level_pri')->where(['level_id' => $levelId])->column('id, pri_id', 'id');
            $this->assign('hasPrivilege', $hasPrivilege);
            $this->assign('privilege', $privilege);
            return $this->fetch();
        }else{
            $privilegeId = $this->request->param('privilegeId');
            $time = date('Y-m-d H:i:s');
            //刪除
            db('lite_score_level_pri')->where(['level_id' => $levelId])->delete();
            foreach ($privilegeId as $key => $value){
                db('lite_score_level_pri')->insert([
                    'pri_id' => $value,
                    'level_id' => $levelId,
                    'create_time' => $time,
                ]);
            }
            $this->success('数据记录保存成功!', '');
        }
    }

}